package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsTabla;
import javax.swing.JOptionPane;

/**
 *
 * @author MK
 */
public class dlgUnidades extends javax.swing.JDialog {

    private ClsMetodos metodos = new ClsMetodos();
    private ClsDatabase bd = new ClsDatabase();

    /**
     * Creates new form dlgUnidades
     *
     * @param parent
     * @param modal
     */
    public dlgUnidades(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);//Centramos la ventana
        setTitle("Unidades");
        metodos._iconJDialog(this);
        _iniciar_U();
        metodos.tablaOcultarcolumnas(tblUnidades, new int[]{0, 3});
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public final void _iniciar_U() {
        txtBuscarU.setText("");
        txtBuscarU.requestFocus();
        _cargarTabla_Unidades();
        metodos.tablaLongitudColumnas(tblUnidades, new int[]{0, 250, 50, 0});
    }

    public void _cargarTabla_Unidades() {
        String nombreBuscar = txtBuscarU.getText().toString();
        metodos.tablaLlenaSql_defecto(tblUnidades,
                "idunidad,nombre,simbolo,estado",
                "FROM unidad "
                + "WHERE nombre like '%" + nombreBuscar + "%' "
                + "ORDER BY nombre asc");
    }

    public void EliminarUnidades() {
        int fila = tblUnidades.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {
            //Confirmamos la eliminacion
            if (JOptionPane.showConfirmDialog(null, "Está seguro que desea eliminar la Unidad seleccionada", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id = tblUnidades.getValueAt(fila, 0).toString();
                boolean seRepite = bd.verif_repite("SELECT idunidad FROM insumo WHERE idunidad='" + id + "'");
//                boolean seRepite2 = bd.verif_repite("SELECT idunidad FROM partida_base_detalle WHERE idunidad='" + id + "'");
                boolean seRepite3 = bd.verif_repite("SELECT idunidad FROM partida_base WHERE idunidad='" + id + "'");
                boolean seRepite4 = bd.verif_repite("SELECT idunidad FROM presupuesto_partida WHERE idunidad='" + id + "'");
                if (!seRepite && !seRepite3 &&!seRepite4) {
                    boolean seElimino = bd.delete("unidad", "idunidad='" + id + "'");
                    if (seElimino) {
                        _cargarTabla_Unidades();
                        //JOptionPane.showMessageDialog(null, "Se elimino el insumo con exito");
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "No se puede eliminar esta Unidad porque ya está siendo utilizada");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Seleccione una Unidad");
        }
    }

    public void editar() {
        dlg_Unidades dialogU = new dlg_Unidades(new javax.swing.JFrame(), true, this, this.tblUnidades);
        dialogU.Editar();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        txtBuscarU = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblUnidades = new javax.swing.JTable();
        btnQuitar_Unidad = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnAgregar_Unidad = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos de Unidades");

        jPanel2.setBackground(new java.awt.Color(225, 235, 247));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanel1.setOpaque(false);

        jLabel8.setText("Nombre:");

        txtBuscarU.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarUKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtBuscarU, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtBuscarU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 516, -1));

        tblUnidades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Cód.", "Descripción", "Abreviatura", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblUnidades.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblUnidades.getTableHeader().setReorderingAllowed(false);
        tblUnidades.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblUnidadesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblUnidades);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 83, 516, 282));

        btnQuitar_Unidad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/borrar.png"))); // NOI18N
        btnQuitar_Unidad.setText("Eliminar");
        btnQuitar_Unidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitar_UnidadActionPerformed(evt);
            }
        });
        jPanel2.add(btnQuitar_Unidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(226, 383, -1, -1));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(424, 383, 102, -1));

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });
        jPanel2.add(btnEditar, new org.netbeans.lib.awtextra.AbsoluteConstraints(118, 383, 90, -1));

        btnAgregar_Unidad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/agregar.png"))); // NOI18N
        btnAgregar_Unidad.setText("Crear");
        btnAgregar_Unidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregar_UnidadActionPerformed(evt);
            }
        });
        jPanel2.add(btnAgregar_Unidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 383, 90, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 280));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtBuscarUKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarUKeyReleased
        _cargarTabla_Unidades();
    }//GEN-LAST:event_txtBuscarUKeyReleased

    private void btnAgregar_UnidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregar_UnidadActionPerformed
        dlg_Unidades dialogU = new dlg_Unidades(new javax.swing.JFrame(), true, this, tblUnidades);
        //dialogU.setTitle("Agregar un Nuevo Insumo");
        dialogU.setVisible(true);
    }//GEN-LAST:event_btnAgregar_UnidadActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        editar();
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnQuitar_UnidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitar_UnidadActionPerformed
        EliminarUnidades();
    }//GEN-LAST:event_btnQuitar_UnidadActionPerformed

    private void tblUnidadesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblUnidadesMouseClicked
        if (evt.getClickCount() == 2) {
            editar();
        }
    }//GEN-LAST:event_tblUnidadesMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgUnidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgUnidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgUnidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgUnidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgUnidades dialog = new dlgUnidades(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar_Unidad;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnQuitar_Unidad;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblUnidades;
    private javax.swing.JTextField txtBuscarU;
    // End of variables declaration//GEN-END:variables
}
